from utilities.redis import captcha_redis as redis_conn


def delete_cachestatus(key):
    valid_status = redis_conn.hget(key, 'status')
    if valid_status:
        valid_status = int(valid_status)
        if valid_status == 0 or valid_status == 1:
            redis_conn.delete(key)
            return True
    return False


def progress_info(key):
    info = redis_conn.hgetall(key)
    delete_cachestatus(key)
    if not info:
        info = {'code': 3, 'message': '无进度信息'}
    try:
        info = {k.decode(): v.decode() for k, v in info.items()}
    except Exception:
        pass
    return info


def unique_operation(key):
    """只允许一个人操作
    例如： a 点击了备份。 b也点击备份时提示有人正在备份。 稍后再试
    """
    status = redis_conn.hget(key, 'status')
    if not status:
        return True
    status = int(status)
    if status in (0, 1):
        return True
    return False
